var matchWidth = printMode ? 170 : 200;
var matchHeight = printMode ? 40 : 130;
var tournamentDrawId = 'tournamentDraw';
var maxMatchPerRound, maxDrawHeight, allPlayers = {}, roundTitle = {},
    allScores = {};
var tournamentDrawClass = 'drawTournament';

/**
 * Initializes global variables.
 */
function initGlobalVariables() {
  maxMatchPerRound = Math.pow(2, numberOfRound - 1);
  maxDrawHeight = (maxMatchPerRound)* matchHeight;
  for (var i = 0; i < allPlayersFromJson.length; i++) {
    allPlayers[allPlayersFromJson[i].idPlayer] = allPlayersFromJson[i];
  }
  allScores = {};
  for (var i = 0; i < allScoresFromJson.length; i++) {
    if (allScores[allScoresFromJson[i].idTournamentMatch] == undefined) {
      allScores[allScoresFromJson[i].idTournamentMatch] = [];
    }
    allScores[allScoresFromJson[i].idTournamentMatch].push(allScoresFromJson[i]);
  }
}

/**
 * Displays draw tournament.
 */
function displayDraw() {
  var drawTournament = $('<div></div>');
  drawTournament.addClass(tournamentDrawClass);
  for (var i = 0; i < allMatches.length; i++) {
    var left = (numberOfRound - allMatches[i].idTournamentRoundType) * matchWidth;
    var currentMatchHeight = maxDrawHeight / Math.pow(2, allMatches[i].idTournamentRoundType - 1);
    var top = currentMatchHeight * (allMatches[i].matchOrder - 1);
    if (printMode) {
      if (allMatches[i].idTournamentRoundType == 6) {
        top += ((allMatches[i].matchOrder % 2 == 0) ? 1 : -1 ) * 
            currentMatchHeight / 4;
      }
    }
    var newMatch = $('<div></div>');
    newMatch.addClass('matchWrapper');
    newMatch.addClass('matchRound' + allMatches[i].idTournamentRoundType);
    newMatch.css('position', 'absolute');
    newMatch.css('top', top);
    newMatch.css('left', left);
    newMatch.css('width', matchWidth);
    newMatch.css('height', currentMatchHeight);
    newMatch.attr('data-idMatch', allMatches[i].idTournamentMatch);
    newMatch.attr('id', getIdFromMatch(i));
    
    var newMatchContainer = $('<div></div>');
    newMatchContainer.addClass('matchContainer');
    newMatchContainer.attr('id', 'matchContainer' + i);
    newMatchContainer.height(currentMatchHeight / 2);
    newMatchContainer.css('top', currentMatchHeight / 4);
    newMatch.append(newMatchContainer);
    
    var newMatchPlayer1 = $('<div></div>');
    newMatchPlayer1.addClass("newMatchPlayer1 newMatchPlayer");
    newMatchPlayer1.html(getPlayerGroupName(1, i));
    newMatchContainer.append(newMatchPlayer1);
    
    var newMatchPlayer2 = $('<div></div>');
    newMatchPlayer2.addClass("newMatchPlayer2 newMatchPlayer");
    newMatchPlayer2.html(getPlayerGroupName(2, i));
    newMatchContainer.append(newMatchPlayer2)
    
    
    newMatchContainer.append(getNewMatchField(newMatchContainer, i));
    
    
    drawTournament.append(newMatch);
  }
  $('#' + tournamentDrawId).append(drawTournament);
  $('.' + tournamentDrawClass).height(maxDrawHeight);
}


/**
 * Gets the block for more information on the match.
 */
function getNewMatchField(newMatchContainer, matchIndex) {
  var newMatchField = $('<div></div>');
  newMatchField.addClass("newMatchField");
  newMatchField.height(matchHeight / (printMode ? 2 : 4));
  newMatchField.css('line-height', (matchHeight / 4 ) + 'px');
  newMatchField.css('top', newMatchContainer.height() / 2 - newMatchField.height() / 2);
  var newMatchFieldLink = $('<a></a>');
  newMatchFieldLink.attr('href', 'index.php?page=Carte+des+terrains&idField=' +
      allMatches[matchIndex].idTournamentField);
  newMatchFieldLink.html(allMatches[matchIndex].fieldName);
  newMatchField.append(newMatchFieldLink);
  newMatchField.append(' ');
  newMatchField.append(getTiming(matchIndex));
  return newMatchField;
}

/**
 * Gets the timing of the match.
 */
function getTiming(matchIndex) {
  var matchTiming = $('<span></span>');
  matchTiming.addClass("matchTiming");
  if (allMatches[matchIndex].date != '0000-00-00') {
    var dateSplitted = allMatches[matchIndex].date.split('-');
    matchTiming.append(dateSplitted[2] + '/' + dateSplitted[1]);
  }
  if (allMatches[matchIndex].hour != '0') {
    matchTiming.append(' - ' + formatTime(allMatches[matchIndex].hour)
        + ':' + formatTime(allMatches[matchIndex].minute));
  }
  return matchTiming;
}

function formatTime(time) {
  return (time < 10 ? '0' : '') + '' + time;
}

/**
 * get Id from match.
 * @returns {String}
 */
function getIdFromMatch(matchIndex) {
  return getMatchId(allMatches[matchIndex].idTournamentRoundType,
      allMatches[matchIndex].matchOrder);  
}


/**
 * get Id from match.
 * @returns {String}
 */
function getMatchId(idTournamentRoundType, matchOrder) {
  return idTournamentRoundType + '-' + matchOrder;  
}

/**
 * Displays winner and scores of matches.
 */
function displayScores() {
  for (var i = 0; i < allMatches.length; i++) {
    if (allMatches[i].winner != 0 && allMatches[i].idTournamentMatch != undefined
        ) {
      if (allMatches[i].matchOrder == 1 && allMatches[i].idTournamentRoundType == 1) {
        displayFinalScoreMatch(i);
      } else {
        displayScoreMatch(i);
      }
    }
  }
}

/**
 * Displays score of a match. 
 */
function displayScoreMatch(indexMatch) {
  var winnerRound = allMatches[indexMatch].idTournamentRoundType - 1;
  var winnerOrder = Math.ceil(allMatches[indexMatch].matchOrder / 2);
  var playerIndex = (allMatches[indexMatch].matchOrder  % 2 == 0) ? 2 : 1;
  
  var winnerBlockId = getMatchId(winnerRound, winnerOrder);
  $('#' + winnerBlockId + ' .newMatchPlayer' + playerIndex).html(
      getPlayerNameWinner(indexMatch) + " " +
      getScoreOfMatch(indexMatch)
      );
}

/**
 * Displays the score of the final
 * @param i Index of the match corresponding to final game.
 */
function displayFinalScoreMatch(indexMatch) {
  var finalGame = $('<div></div>');
  finalGame.addClass('finalGame');
  finalGame.html(getPlayerNameWinner(indexMatch) + " " +
      getScoreOfMatch(indexMatch))
  $('#1-1 .newMatchField').append(finalGame);
}


/**
 * 
 * @param matchIndex
 * @returns
 */
function getPlayerNameWinner(matchIndex) {
  var idTournamentMatch = allMatches[matchIndex].idTournamentMatch;
  var winner = allMatches[matchIndex].winner;
  return getPlayerGroupName(winner, matchIndex);
}

/**
 * 
 */
function getPlayerGroupName(indexPlayer, matchIndex) {
  var PlayerGroupName = getPlayerName(allMatches[matchIndex]['idPlayer' + indexPlayer]);
  if (parseInt(allMatches[matchIndex]['idPlayer' + (parseInt(indexPlayer) + 2)]) != 0 &&
      allMatches[matchIndex]['idPlayer' + (parseInt(indexPlayer) + 2)] != undefined) {
    PlayerGroupName += ' / ' +
        getPlayerName(allMatches[matchIndex]['idPlayer' + (parseInt(indexPlayer) + 2)]);
  }
  return PlayerGroupName;
}

/**
 * Displays round title (final, semi-final...).
 */
function displayRoundTitle() {
  for (var i = 0; i < allMatches.length; i++) {
    roundTitle[allMatches[i].idTournamentRoundType] = allMatches[i].tournamentRoundTypeName; 
  }
  var roundTitleWrapper = $('<div></div>');
  roundTitleWrapper.addClass('roundTitleWrapper');
  for (var i = 1; i < numberOfRound + 1; i++) {
    var roundTitleEl = $('<div></div>');
    var roundTitleTextEl = $('<div></div>');
    roundTitleTextEl.text(decodeURI(roundTitle[i]));
    roundTitleTextEl.addClass('roundTitleText');
    roundTitleEl.append(roundTitleTextEl);
    roundTitleEl.addClass('roundTitle');
    roundTitleEl.width(matchWidth);
    roundTitleEl.css("left", matchWidth * (numberOfRound - i));
    roundTitleWrapper.append(roundTitleEl);
  }
  $('#' + tournamentDrawId).prepend(roundTitleWrapper);
  $('.roundTitleWrapper').sticky({topSpacing:0});
}


/**
 * Gets player name form its id.
 * @returns {String}
 */
function getPlayerName(idPlayer) {
  var playerWrapperEl = $('<div></div>');
  var playerEl = $('<a></a>');
  playerEl.attr('href', 'index.php?page=player&id=' + idPlayer);
  playerEl.addClass('playerName');
  playerEl.html(allPlayers[idPlayer] == undefined ? "" :
      allPlayers[idPlayer].playerSurname + " " + allPlayers[idPlayer].playerLastname);
  playerWrapperEl.append(playerEl);
  return playerWrapperEl.html(); 
}

/**
 * Gets score of match from its id.
 * @returns {String}
 */
function getScoreOfMatch(matchIndex) {
  var idMatch = allMatches[matchIndex].idTournamentMatch ;
  if (allMatches[matchIndex].playerKO != 0) {
    return " (par KO)";
  }
  if (allScores[idMatch] == undefined) {
    return;
  }
  var score = $('<span></span>');
  var nbMaxOfSet = allScores[idMatch].length / 2;
  for (var i = 1; i < nbMaxOfSet + 1; i++) {
    var set = $('<span class="set' + i + '"></span>');
    set.addClass('set' + i);
    set.append('<span class="player1">11</span>');
    set.append('/');
    set.append('<span class="player2">9</span> ');
    score.append(set);
  }
  for (var i = 0; i < allScores[idMatch].length; i ++) {
    var set = allScores[idMatch][i].setIndex;
    var player = isScoreOfWinner(allScores[idMatch][i], allMatches[matchIndex]) ? 1 : 2;
    score.find(".set" + set + " .player" + player).html(allScores[idMatch][i].score);
  }
  return score.html();
}

/**
 * 
 * @param score
 * @param match
 * @returns {Boolean}
 */
function isScoreOfWinner(score, match) {
  if (score.idPlayer01 == match.idPlayer1) {
    return match.winner == 1;
  } else {
    return match.winner == 2;
  }
}

/**
 * Displays title of the tournament.
 */
function displayTitleTournament() {
  var title = $('<div></div>');
  title.addClass('tournamentTitle');
  var tournamentNameEl = $('<span></span>');
  tournamentNameEl.addClass('tournamentName');
  tournamentNameEl.html(tournamentName);
  
  title.append(tournamentNameEl);
  title.append('<span> - </span> ');
  for (var i = 0; i < allTournamentDraws.length; i++) {
	  var tournamentDrawTypeNameEl = $('<span></span>');
	  tournamentDrawTypeNameEl.addClass('tournamentDrawTypeName');
	  if (allTournamentDraws[i].idTournamentDraw == idTournamentDraw) {
		  tournamentDrawTypeNameEl.addClass('currentTournamentDrawTypeName');
	  }
	  tournamentDrawTypeNameEl.html(allTournamentDraws[i].tournamentDrawTypeName);
	  
	  var onClickEl = (function(a) {
		  return function() {
			  launchTournamentDraw(a);
			  laCurrentUrl("clickSwitchTournamentDraw", a);
		  }
	  }) (allTournamentDraws[i].idTournamentDraw)
	  
	  tournamentDrawTypeNameEl.click(onClickEl);
	  
	  title.append(tournamentDrawTypeNameEl);
	  if (i < allTournamentDraws.length - 1) {
		  title.append(" - ");
	  }
  }
  $('#' + tournamentDrawId).prepend(title);
}


/**
 * 
 * @param idTournamentDraw
 */
function launchTournamentDraw(idTournamentDraw) {
	$.get("page/getMatchJsonAjax.php?idTournamentDraw=" + idTournamentDraw, function(data) {
		$("#resultWrapperDebug").html(data);
		launchDrawDisplay();
	})
}

/**
 * Displays only the winner of the tournament. 
 */
function displayWinnerOnly() {
  $('#' + tournamentDrawId).append(
      'Vainqueur : ' + getPlayerNameWinner(0));
}

/**
 * Launches the display of a draw.
 */
$(document).ready(function() {
  launchDrawDisplay();
});

function launchDrawDisplay() {
  var currentHeight = $('#' + tournamentDrawId).height();
  $('#' + tournamentDrawId).height(currentHeight);
  $('#' + tournamentDrawId).html('');
  initGlobalVariables();
  if (allMatches.length == 1) {
    displayWinnerOnly();
  } else {
    displayDraw();
    displayRoundTitle();
    displayScores();
  }
  displayTitleTournament();
  if (typeof(scrollToMatch) == 'function') {
    scrollToMatch();
  }
  if (typeof(adminOn) != 'undefined') {
    launchAdmin();   
  }
  $('#' + tournamentDrawId).height("");
}